package 算法.leetcode.offer;

import java.util.Stack;

/**
 * @author lchenglong
 * @date 2022/4/27
 */
public class Offer31 {

    public static void main(String[] args) {
        Offer31 instance = new Offer31();
            boolean ans = instance.validateStackSequences(new int[]{1,2,3,4,5}, new int[]{4,5,1,3,2});
        System.out.println(ans);
    }
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        // 边界条件
        if (pushed==popped)return true;
        if (popped.length!=pushed.length)return false;
        // 定义一个栈
        Stack<Integer> stack = new Stack<>();
        int j =0;
        for (int i=0;i<popped.length;) {
            if (!stack.isEmpty() && stack.peek() == popped[i]){
                stack.pop();
                System.out.println("stack.pop(): "+popped[i]);
                i++;
                continue;
            } else if (j ==pushed.length)break;
            while (j<pushed.length) {
                if (!stack.isEmpty() && stack.peek() == popped[i]){
                    stack.pop();
                    System.out.println("stack.pop(): "+popped[i]);
                    i++;
                    continue;
                }
                stack.push(pushed[j]);
                System.out.println("stack.push(): "+pushed[j]);
                j++;
            }


        }
        return stack.empty();
    }
}
